package com.example.fresh_market.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.android.volley.Request;
import com.bumptech.glide.request.RequestOptions;
import com.example.fresh_market.databinding.ActivityUserEditBinding;
import com.example.fresh_market.entity.UserDO;
import com.example.fresh_market.entity.UserInfo;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class UserEditActivity extends AppCompatActivity {
    private Context mContext;
    private ActivityUserEditBinding binding;
    private Spinner spinner;
    private String role = "USER";
    private long userId = 0L;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        binding = ActivityUserEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        spinner = binding.userRoleSpinner;
        List<Object> data = new ArrayList<>();
        data.add("普通用户");
        data.add("管理员");
        data.add("超级管理员");
        ArrayAdapter<Object> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, data);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String roleStr = (String) data.get(position);
                switch (roleStr) {
                    case "普通用户":
                        role = "USER";
                        break;
                    case "管理员":
                        role = "ADMIN";
                        break;
                    case "超级管理员":
                        role = "SUDO";
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        userId = getIntent().getLongExtra("userId", 0L);
        if (userId != 0L) {
            initData(userId);
        }
        initEvent();
    }

    private void initData(Long userId) {
        HttpUtil.get(mContext, "/admin/user/" + userId, response -> {
            ApiResponse<UserDO> apiResponse = new Gson().fromJson(response, new TypeToken<ApiResponse<UserDO>>() {
            }.getType());
            if (apiResponse.getCode() == 200) {
                UserDO userInfo = apiResponse.getData();
                binding.userIdTextView.setText(String.valueOf(userInfo.getId()));
                binding.usernameEditText.setText(userInfo.getUsername());
                binding.nicknameEditText.setText(userInfo.getNickname());
                binding.phoneEditText.setText(userInfo.getPhone());
                binding.passwordEditText.setText(userInfo.getPassword());
                binding.emailEditText.setText(userInfo.getEmail());
                binding.addressEditText.setText(userInfo.getAddress());
                binding.remarkEditText.setText(userInfo.getRemark());
                binding.ageEditText.setText(String.valueOf(userInfo.getAge()));
                spinner.setSelection(userInfo.getRoleName().equals("用户") ? 0 : userInfo.getRoleName().equals("管理员") ? 1 : 2);
                if (userInfo.getGender() == 1) {
                    binding.maleRadioButton.setChecked(true);
                } else if (userInfo.getGender() == 2) {
                    binding.femaleRadioButton.setChecked(true);
                } else {
                    binding.otherRadioButton.setChecked(true);
                }
                if (StringUtils.isNotBlank(userInfo.getAvatar())) {
                    HttpUtil.loadImage(binding.userAvatar, userInfo.getAvatar(), new RequestOptions());
                }
            }
        });
    }

    private void initEvent() {
        binding.userAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, 666);
        });
        binding.saveButton.setOnClickListener(v -> {
            // 获取图片
            Drawable drawable = binding.userAvatar.getDrawable();
            String cover = null;
            if (drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                cover = Base64.getEncoder().encodeToString(stream.toByteArray());
            }
            UserInfo userInfo = UserInfo.builder()
                    .username(binding.usernameEditText.getText().toString())
                    .nickname(binding.nicknameEditText.getText().toString())
                    .phone(binding.phoneEditText.getText().toString())
                    .password(binding.passwordEditText.getText().toString())
                    .email(binding.emailEditText.getText().toString())
                    .address(binding.addressEditText.getText().toString())
                    .remark(binding.remarkEditText.getText().toString())
                    .age(binding.ageEditText.getText().toString())
                    .status(binding.statusCheckBox.isChecked())
                    .role(role)
                    .gender(binding.maleRadioButton.isChecked() ? 1 : binding.femaleRadioButton.isChecked() ? 2 : 3)
                    .avatar(cover)
                    .build();
            if (!binding.userIdTextView.getText().toString().isEmpty()) {
                userInfo.setId(Long.valueOf(binding.userIdTextView.getText().toString()));
            }
            Gson gson = new Gson();
            int method = userId == 0L ? Request.Method.POST : Request.Method.PUT;
            HttpUtil.sendJsonRequest(mContext, method, "/admin/user", gson.toJson(userInfo), response -> {
                ApiResponse apiResponse = gson.fromJson(response.toString(), ApiResponse.class);
                if (apiResponse.getCode() == 200) {
                    ToastUtil.showToast(mContext, "保存成功");
                    Intent intent = new Intent(mContext, ProductActivity.class);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 666 && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                try (InputStream inputStream = getContentResolver().openInputStream(imageUri)) {
                    if (inputStream != null) {
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        binding.userAvatar.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
    }
}
